using System;
using System.Collections.Generic;
using UnityEngine;
using QFramework;
using Sirenix.OdinInspector;
using Random = UnityEngine.Random;

namespace Survivor
{

	public partial class DropItemManager : ViewController
	{
		public static DropItemManager Instance;
		public List<RandomInfo> dropItemInfos = new();
		[ShowInInspector,ReadOnly] public List<int> preWeightSum = new();
		private void Awake()
		{
			Instance = this;
		}

		void Start()
		{
			// Code Here
			InitWeight();
		}

		public void InitWeight()
		{
			if (dropItemInfos.Count !=0)
			{
				dropItemInfos[0].Reset(); 
				preWeightSum.Add(dropItemInfos[0].generateWeight);
				for (int i = 1; i < dropItemInfos.Count; i++)
				{
					dropItemInfos[i].Reset();
					preWeightSum.Add(preWeightSum[i-1]+dropItemInfos[i].generateWeight);
				}
			}
		}

		public int GetRandomIndex()
		{
			int sumWeight = preWeightSum[^1];  // 最后一个
			int ramdom = Random.Range(0, sumWeight);
			for (int i = 0; i < preWeightSum.Count; i++)
			{
				if (ramdom < preWeightSum[i])
				{
					return i;
				}
			}
			return 0;
		}

		private int _forceDropItem = -1;
		public void GenerateRandomDropItem(Vector2 position)
		{
			if (dropItemInfos.Count ==0) return;
			
			// 强制掉落指定物品一次
			var index = _forceDropItem;
			if (index  == -1)
			{
				index = GetRandomIndex();
			}
			else
			{
				_forceDropItem = -1;
			}
			dropItemInfos[index].prefab.Instantiate().Position(position).Show();
		}
		public void SetNextDropItem(int index)
		{
			this._forceDropItem = index;
		}
	}
}
